package com.yuji.aacar.widgets.countdownbutton;

import android.os.CountDownTimer;

import java.util.Observable;
import java.util.Observer;

/**
 * <li>Package: {@link CountDownHelper}
 * <li>Author: cyh
 * <li>Date: 2017/6/19 16:19
 * <li>Discription: 倒计时帮助了
 */

public class CountDownHelper extends CountDownTimer {
    private static CountDownHelper countDownHelper;//倒计时帮助类，单例

    private static long countDownTime;//倒计时总时间时间

    private CountDownObservable observable;//发送倒计时通知和结束通知

    /**
     * 获得countDownHelper对象
     *
     * @param millisInFuture    倒计时总时间（毫秒单位）
     * @param countDownInterval 倒计时间隔时间（毫秒单位）
     * @return
     */
    public static synchronized CountDownHelper getInstance(long millisInFuture, long countDownInterval) {
        if (countDownHelper == null) {
            countDownTime = millisInFuture;
            countDownHelper = new CountDownHelper(millisInFuture, countDownInterval);
        }
        return countDownHelper;
    }

    private CountDownHelper(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
        observable = new CountDownObservable();
    }

    /**
     * 间隔回调，l一般为1000毫秒
     *
     * @param l
     */
    @Override
    public void onTick(long l) {
        observable.setChange(l);
    }

    /**
     * 倒计时结束回调
     */
    @Override
    public void onFinish() {
        observable.setChange(0);
        observable.deleteObservers();
    }

    /**
     * 开始倒计时，先取消后开始
     */
    public void startCountDown(){
        cancel();
        observable.setChange(countDownTime);
        start();
    }

    /**
     * 绑定观察者并开始倒计时
     *
     * @param o
     */
    public void addObserable(Observer o) {
        observable.addObserver(o);
    }

    public static class CountDownObservable extends Observable {
        public void setChange(long countDownTime) {
            notifyObservers(countDownTime);
            setChanged();
        }
    }
}
